package org.lanyu.springainovel.common.config;

import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.entity.AiModel;
import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.common.service.AiModelService;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import com.alibaba.fastjson.JSONObject;

/**
 * AI模型初始化服�?
 * 在应用启动时初始化默认的对话模型、嵌入模型和向量存储
 */
@Slf4j
@Service
public class AIModelInitService implements ApplicationRunner {

    @Autowired
    private AiModelService modelConfigService;

    @Autowired
    private ChatModelManager chatModelManager;

    @Autowired
    private EmbeddingModelManager embeddingModelManager;

    @Autowired
    private VectorStoreManager vectorStoreManager;

    @Override
    public void run(ApplicationArguments args) {
        log.info("开始初始化AI模型配置...");

        try {
            // 获取聊天模型
            List<AiModel> chatModels = modelConfigService.findAllActive("对话");
            if (!CollectionUtils.isEmpty(chatModels)) {
                for (AiModel aiModel : chatModels) {
                    initializeDefaultChatModel(aiModel);
                }
            }
            // 获取聊天模型
            List<AiModel> enbeddingModels = modelConfigService.findAllActive("嵌入");
            if (!CollectionUtils.isEmpty(enbeddingModels)) {
                for (AiModel aiModel : enbeddingModels) {
                    initializeDefaultEmbeddingModel(aiModel);
                }
            }
            log.info("AI模型配置初始化完成");
        } catch (Exception e) {
            log.error("AI模型配置初始化失败");
            // 不抛出异常，允许应用继续启动
        }
    }

    /**
     * 初始化默认对话模�?
     */
    private void initializeDefaultChatModel(AiModel aiModel) {
        try {
            chatModelManager.getOrCreateChatModel(aiModel);
            log.info("初始化默认对话模型成功 {}", aiModel.getName());
        } catch (Exception e) {
            log.error("初始化默认对话模型失败 {}", aiModel.getName(), e);
        }
    }

    /**
     * 初始化默认嵌入模型
     */
    private void initializeDefaultEmbeddingModel(AiModel aiModel) {
        try {
            EmbeddingModel embeddingModel1 = embeddingModelManager.getOrCreateEmbeddingModel(aiModel);
            log.info("初始化默认嵌入模型成�? {}", aiModel.getName());
            initializeDefaultVectorStore(embeddingModel1);
        } catch (Exception e) {
            log.error("初始化默认嵌入模型失�? {}", aiModel.getName(), e);
        }
    }

    /**
     * 初始化默认向量存储
     */
    private void initializeDefaultVectorStore(EmbeddingModel embeddingModel) {
        try {
            // 检查向量存储是否启用
            if (!vectorStoreManager.isVectorStoreEnabled()) {
                log.info("ES向量存储功能已禁用，跳过初始化");
                return;
            }
            
            vectorStoreManager.getDefaultVectorStore(embeddingModel);
            log.info("初始化默认向量存储成功");
        } catch (Exception e) {
            log.error("初始化默认向量存储失败",e);
        }
    }

    /**
     * 处理模型配置更新事件
     * 当模型配置被修改时，清除相关缓存并重新创建模型实�?
     *
     * @param modelConfig 更新后的模型配置
     */
    public void handleModelConfigUpdate(AiModel modelConfig) {
        try {
            log.info("处理模型配置更新: {} - {}", modelConfig.getName(), modelConfig.getId());

            // 清除对应的模型缓�?
            if ("对话".equals(modelConfig.getType())) {
                chatModelManager.getOrCreateChatModel(modelConfig);
            } else if ("嵌入".equals(modelConfig.getType())) {
                EmbeddingModel embeddingModel = embeddingModelManager.getOrCreateEmbeddingModel(modelConfig);
                vectorStoreManager.getDefaultVectorStore(embeddingModel);
                log.info("重新加载当前默认嵌入模型: {}", modelConfig.getName());
            }
            log.info("模型配置更新处理完成: {}", modelConfig.getName());
        } catch (Exception e) {
            log.error("处理模型配置更新失败: {} - {}", modelConfig.getName(), e.getMessage(), e);
        }
    }

    /**
     * 处理模型配置删除事件
     * 当模型配置被删除时，清除相关缓存
     *
     * @param modelId   被删除的模型ID
     * @param modelType 模型类型
     */
    public void handleModelConfigDelete(Long modelId, String modelType) {
        try {
            log.info("处理模型配置删除: {} - {}", modelId, modelType);

            if ("对话".equals(modelType)) {
                chatModelManager.clearCache(modelId);
            } else if ("嵌入".equals(modelType)) {
                embeddingModelManager.clearCache(modelId);
            }
            log.info("模型配置删除处理完成: {}", modelId);
        } catch (Exception e) {
            log.error("处理模型配置删除失败: {} - {}", modelId, e.getMessage(), e);
        }
    }
    
    /**
     * 获取默认向量存储
     * 
     * @return 默认向量存储实例
     */
    public VectorStore getDefaultVectorStore() {
        try {
            // 获取默认的嵌入模�?
            List<AiModel> embeddingModels = modelConfigService.findAllActive("嵌入");
            if (!CollectionUtils.isEmpty(embeddingModels)) {
                AiModel defaultModel = embeddingModels.get(0);
                EmbeddingModel embeddingModel = embeddingModelManager.getOrCreateEmbeddingModel(defaultModel);
                return vectorStoreManager.getDefaultVectorStore(embeddingModel);
            }
            log.warn("未找到默认的嵌入模型");
            return null;
        } catch (Exception e) {
            log.error("获取默认向量存储失败", e);
            return null;
        }
    }
    
    /**
     * 根据用户获取其自定义的向量存储
     * 
     * @param user 用户对象
     * @param indexName 索引名称
     * @return 向量存储实例
     */
    public VectorStore getVectorStoreByUser(User user, String indexName) {
        try {
            // 检查向量存储是否启用
            if (!vectorStoreManager.isVectorStoreEnabled()) {
                log.info("ES向量存储功能已禁用，使用内存向量存储");
                // 获取默认的嵌入模型并创建内存向量存储
                List<AiModel> embeddingModels = modelConfigService.findAllActive("嵌入");
                if (!CollectionUtils.isEmpty(embeddingModels)) {
                    AiModel defaultModel = embeddingModels.get(0);
                    EmbeddingModel embeddingModel = embeddingModelManager.getOrCreateEmbeddingModel(defaultModel);
                    return vectorStoreManager.getDefaultVectorStore(embeddingModel);
                }
                return null;
            }
            
            if (user == null || user.getCustom() == null) {
                log.info("用户或用户自定义配置为空，使用默认向量存储");
                return getDefaultVectorStore();
            }
            
            // 从用户自定义配置中获取嵌入模型ID
            JSONObject custom = user.getCustom();
            String embeddingModelId = custom.getString("embeddingModelId");
            
            if (StringUtils.hasText(embeddingModelId)) {
                try {
                    Long modelId = Long.parseLong(embeddingModelId);
                    AiModel embeddingModelConfig = modelConfigService.findById(modelId);
                    

                    if (embeddingModelConfig != null && "嵌入".equals(embeddingModelConfig.getType()) && 1 == embeddingModelConfig.getStatus()) {
                        // 获取或创建用户特定的嵌入模型
                        EmbeddingModel embeddingModel = embeddingModelManager.getOrCreateEmbeddingModel(embeddingModelConfig);
                        
                        // 使用嵌入模型的维度，如果没有设置则使用默认值
                        int dimensions = custom.getIntValue("vectorDimensions");
                        if (dimensions <= 0) {
                            dimensions = 1024;
                        }
                        
                        // 创建用户特定的向量存储
                        return vectorStoreManager.getOrCreateVectorStore(embeddingModel, indexName, dimensions);
                    }
                    log.warn("未找到有效的嵌入模型配置，ID: {}", embeddingModelId);
                } catch (NumberFormatException e) {
                    log.error("无效的模型ID格式: {}", embeddingModelId, e);
                }
            } else {
                log.info("用户未配置自定义嵌入模型，使用默认向量存储");
            }
            
            // 如果无法获取用户自定义模型，则使用默认向量存储
            return getDefaultVectorStore();
        } catch (Exception e) {
            log.error("根据用户获取向量存储失败", e);
            // 出错时返回默认向量存储
            return getDefaultVectorStore();
        }
    }
}
